<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MQTT控制面板 - Vue</title>
    <!-- Element UI CSS -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- Vue -->
    <script src="https://unpkg.com/vue@2/dist/vue.js"></script>
    <!-- Element UI JS -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <!-- MQTT -->
    <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
</head>
<body>
    <div id="app">
        <el-container>
            <el-main>
                <el-card class="box-card">
                    <div slot="header" class="clearfix">
                        <span style="font-size: 20px; font-weight: bold;">MQTT控制面板</span>
                    </div>
                    
                    <!-- MQTT连接参数配置 -->
                    <el-form :model="mqttConfig" label-width="120px" size="small">
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="服务器地址">
                                    <el-input v-model="mqttConfig.serverAddress" placeholder="请输入服务器地址"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="WebSocket端口">
                                    <el-input-number v-model="mqttConfig.wsPort" :min="1" :max="65535" style="width: 100%"></el-input-number>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="MQTT端口">
                                    <el-input-number v-model="mqttConfig.mqttPort" :min="1" :max="65535" style="width: 100%"></el-input-number>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="保活时间(秒)">
                                    <el-input-number v-model="mqttConfig.keepalive" :min="10" :max="300" style="width: 100%"></el-input-number>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="客户端ID">
                                    <el-input v-model="mqttConfig.clientId" placeholder="自动生成或手动输入">
                                        <el-button slot="append" @click="generateClientId">生成</el-button>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="发布主题">
                                    <el-input v-model="mqttConfig.topic" placeholder="请输入主题"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="用户名">
                                    <el-input v-model="mqttConfig.username" placeholder="可选，留空则无认证"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="密码">
                                    <el-input v-model="mqttConfig.password" type="password" placeholder="可选，留空则无认证" show-password></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                    
                    <!-- 连接状态 -->
                    <el-divider></el-divider>
                    <el-row :gutter="20" style="margin-bottom: 20px;">
                        <el-col :span="12">
                            <el-tag :type="connectionStatus.type" size="medium">
                                {{ connectionStatus.text }}
                            </el-tag>
                        </el-col>
                        <el-col :span="12" style="text-align: right;">
                            <el-button-group>
                                <el-button type="primary" :loading="connecting" @click="connectMQTT" :disabled="connected">连接</el-button>
                                <el-button type="danger" @click="disconnectMQTT" :disabled="!connected">断开</el-button>
                            </el-button-group>
                        </el-col>
                    </el-row>
                    
                    <!-- 控制按钮 -->
                    <el-divider></el-divider>
                    <el-row style="text-align: center; margin-bottom: 20px;">
                        <el-button 
                            :type="ledActive ? 'success' : 'warning'" 
                            size="large" 
                            @click="sendLedCommand" 
                            :disabled="!connected || ledActive" 
                            :icon="ledActive ? 'el-icon-sunny' : 'el-icon-turn-off'">
                            {{ ledActive ? '闪光灯已亮' : '点亮闪光灯' }}
                        </el-button>
                    </el-row>
                    
                    <!-- 摄像头控制 -->
                    <el-divider>摄像头控制</el-divider>
                    
                    <!-- 时间设置 -->
                    <el-row style="justify-content: center; margin-bottom: 15px;">
                        <el-col :span="8" style="text-align: center;">
                            <div style="display: flex; align-items: center; justify-content: center;">
                                <span style="margin-right: 10px; color: #606266; font-size: 14px;">转动时间：</span>
                                <el-input-number 
                                    v-model="cameraTime" 
                                    :min="0.1" 
                                    :max="5" 
                                    :step="0.1" 
                                    :precision="1"
                                    size="small"
                                    style="width: 120px">
                                </el-input-number>
                                <span style="margin-left: 5px; color: #909399; font-size: 12px;">秒</span>
                            </div>
                        </el-col>
                    </el-row>
                    
                    <div style="display: flex; justify-content: center; align-items: flex-start; gap: 30px;">
                        <!-- 摄像头控制区域 -->
                        <div class="camera-control">
                            <!-- 上 -->
                            <el-row style="justify-content: center; margin-bottom: 10px;">
                                <el-button 
                                    type="primary" 
                                    size="medium" 
                                    @click="sendCameraCommand('up')" 
                                    :disabled="!connected" 
                                    icon="el-icon-top"
                                    class="camera-btn">
                                    上
                                </el-button>
                            </el-row>
                            
                            <!-- 左右 -->
                            <el-row style="justify-content: space-between; align-items: center; margin-bottom: 10px;">
                                <el-button 
                                    type="primary" 
                                    size="medium" 
                                    @click="sendCameraCommand('left')" 
                                    :disabled="!connected" 
                                    icon="el-icon-back"
                                    class="camera-btn camera-side">
                                    左
                                </el-button>
                                
                                <el-button 
                                    type="primary" 
                                    size="medium" 
                                    @click="sendCameraCommand('right')" 
                                    :disabled="!connected" 
                                    icon="el-icon-right"
                                    class="camera-btn camera-side">
                                    右
                                </el-button>
                            </el-row>
                            
                            <!-- 下 -->
                            <el-row style="justify-content: center;">
                                <el-button 
                                    type="primary" 
                                    size="medium" 
                                    @click="sendCameraCommand('down')" 
                                    :disabled="!connected" 
                                    icon="el-icon-bottom"
                                    class="camera-btn">
                                    下
                                </el-button>
                            </el-row>
                            
                            <!-- 拍照按钮 -->
                            <el-row style="justify-content: center; margin-top: 15px;">
                                <el-button 
                                    type="success" 
                                    size="medium" 
                                    @click="takePhoto" 
                                    :disabled="!connected" 
                                    icon="el-icon-camera"
                                    class="photo-btn">
                                    拍照
                                </el-button>
                            </el-row>
                        </div>
                        
                        <!-- 图片显示区域 -->
                        <div class="photo-display">
                            <div class="photo-container">
                                <div v-if="!photoData.imageUrl" class="photo-placeholder">
                                    <i class="el-icon-picture" style="font-size: 48px; color: #c0c4cc;"></i>
                                    <p style="color: #909399; margin-top: 10px;">暂无图片</p>
                                </div>
                                <div v-else>
                                    <img :src="photoData.imageUrl" alt="拍摄的照片" class="photo-image" @click="showFullPhoto">
                                    <div class="photo-info">
                                        <p><strong>设备:</strong> {{ photoData.device }}</p>
                                        <p><strong>时间:</strong> {{ formatTimestamp(photoData.timestamp) }}</p>
                                        <p><strong>文件名:</strong> {{ photoData.filename }}</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 图片预览对话框 -->
                    <el-dialog :visible.sync="showPhotoDialog" width="80%" center>
                        <img v-if="photoData.imageUrl" :src="photoData.imageUrl" style="width: 100%; height: auto;" alt="照片预览">
                    </el-dialog>
                    
                    <!-- 日志区域 -->
                    <el-divider>操作日志</el-divider>
                    <el-card class="log-card">
                        <div class="log-content" ref="logContent">
                            <div v-for="(log, index) in logs" :key="index" class="log-item">
                                <span class="log-time">[{{ log.time }}]</span>
                                <span class="log-message">{{ log.message }}</span>
                            </div>
                        </div>
                        <div style="text-align: right; margin-top: 10px;">
                            <el-button size="mini" @click="clearLogs">清空日志</el-button>
                        </div>
                    </el-card>
                </el-card>
            </el-main>
        </el-container>
    </div>

    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    mqttConfig: {
                        serverAddress: '82.157.22.162',
                        wsPort: 8083,
                        mqttPort: 1883,
                        clientId: '',
                        username: '',
                        password: '',
                        keepalive: 60,
                        topic: 'maixcam_cmd',
                        topdata: 'maixcam_data'
                    },
                    cameraTime: 0.5, // 摄像头转动时间（秒）
                    photoData: {
                        imageUrl: '',
                        device: '',
                        timestamp: 0,
                        filename: ''
                    },
                    showPhotoDialog: false,
                    ledActive: false, // 闪光灯激活状态
                    client: null,
                    connected: false,
                    connecting: false,
                    logs: []
                }
            },
            computed: {
                connectionStatus() {
                    if (this.connecting) {
                        return { type: 'warning', text: '连接中...' };
                    } else if (this.connected) {
                        return { type: 'success', text: '已连接' };
                    } else {
                        return { type: 'danger', text: '未连接' };
                    }
                }
            },
            mounted() {
                this.generateClientId();
                this.addLog('页面已加载，请配置MQTT参数后点击连接');
            },
            methods: {
                // 生成客户端ID
                generateClientId() {
                    this.mqttConfig.clientId = 'web_client_' + Math.random().toString(16).substr(2, 8);
                },
                
                // 添加日志
                addLog(message) {
                    const timestamp = new Date().toLocaleTimeString();
                    this.logs.push({
                        time: timestamp,
                        message: message
                    });
                    
                    // 自动滚动到底部
                    this.$nextTick(() => {
                        if (this.$refs.logContent) {
                            this.$refs.logContent.scrollTop = this.$refs.logContent.scrollHeight;
                        }
                    });
                },
                
                // 清空日志
                clearLogs() {
                    this.logs = [];
                },
                
                // 连接MQTT服务器
                connectMQTT() {
                    if (!this.mqttConfig.serverAddress || !this.mqttConfig.wsPort) {
                        this.$message.error('请填写服务器地址和端口');
                        return;
                    }
                    
                    this.connecting = true;
                    this.addLog('正在连接MQTT服务器...');
                    
                    try {
                        const options = {
                            port: this.mqttConfig.wsPort,
                            clientId: this.mqttConfig.clientId,
                            username: this.mqttConfig.username,
                            password: this.mqttConfig.password,
                            keepalive: this.mqttConfig.keepalive,
                            clean: true
                        };
                        
                        const url = `ws://${this.mqttConfig.serverAddress}:${this.mqttConfig.wsPort}/mqtt`;
                        this.client = mqtt.connect(url, options);
                        
                        // 连接成功事件
                        this.client.on('connect', () => {
                            this.connected = true;
                            this.connecting = false;
                            this.addLog('MQTT连接成功!');
                            
                            // 订阅接收数据的主题
                            this.client.subscribe('maixcam_data', (err) => {
                                if (err) {
                                    console.error('订阅主题失败:', err);
                                    this.addLog('订阅maixcam_data主题失败: ' + err.message);
                                } else {
                                    console.log('订阅主题成功: maixcam_data');
                                    this.addLog('✓ 已订阅接收主题: maixcam_data');
                                }
                            });
                            
                            this.$message.success('MQTT连接成功!');
                        });
                        
                        // 连接错误事件
                        this.client.on('error', (err) => {
                            this.connected = false;
                            this.connecting = false;
                            this.addLog('MQTT连接错误: ' + err.message);
                            this.$message.error('MQTT连接错误: ' + err.message);
                        });
                        
                        // 断开连接事件
                        this.client.on('close', () => {
                            this.connected = false;
                            this.connecting = false;
                            this.addLog('MQTT连接已断开');
                            this.$message.warning('MQTT连接已断开');
                        });
                        
                        // 接收消息事件
                        this.client.on('message', (topdata, message) => {
                            const messageString = message.toString();
                            
                            // 打印到控制台
                            console.log('=== MQTT 收到消息 ===');
                            console.log('主题:', topdata);
                            console.log('原始消息:', messageString);
                            
                            this.addLog(`收到消息 - 主题: ${topdata}`);
                            this.addLog(`原始消息: ${messageString}`);
                            
                            // 只处理来自 maixcam_data 主题的消息
                            if (topdata === 'maixcam_data') {
                                try {
                                    const data = JSON.parse(messageString);
                                    console.log('解析后JSON:', data);
                                    this.addLog(`解析JSON成功:`);
                                    
                                    // 打印所有字段
                                    Object.keys(data).forEach(key => {
                                        if (key === 'image_data' || key === 'data') {
                                            // 如果是图片数据，只显示长度
                                            console.log(`  ${key}: [base64 数据长度: ${data[key] ? data[key].length : 0}]`);
                                            this.addLog(`  ${key}: [base64数据长度: ${data[key] ? data[key].length : 0}]`);
                                        } else {
                                            console.log(`  ${key}:`, data[key]);
                                            this.addLog(`  ${key}: ${JSON.stringify(data[key])}`);
                                        }
                                    });
                                    
                                    // 判断消息类型
                                    if (data.type === 'heartbeat') {
                                        console.log('消息类型: 心跳');
                                        this.addLog('❤️ 收到心跳消息');
                                    } else if (data.type === 'photo') {
                                        console.log('消息类型: 拍照');
                                        this.addLog('📷 收到拍照相关消息');
                                        
                                        // 处理图片数据
                                        let imageData = null;
                                        if (data.image_data) {
                                            imageData = data.image_data;
                                        } else if (data.data) {
                                            imageData = data.data;
                                        } else if (typeof data === 'string' && data.length > 100) {
                                            // 如果整个data就是一个base64字符串
                                            imageData = data;
                                        }
                                        
                                        if (imageData) {
                                            console.log('图片数据长度:', imageData.length);
                                            
                                            // 检查是否已经包含data:image前缀
                                            let imageUrl;
                                            if (imageData.startsWith('data:image/')) {
                                                imageUrl = imageData;
                                            } else {
                                                imageUrl = `data:image/jpeg;base64,${imageData}`;
                                            }
                                            
                                            this.photoData = {
                                                imageUrl: imageUrl,
                                                device: data.device || 'MaixCAM',
                                                timestamp: data.timestamp || Math.floor(Date.now() / 1000),
                                                filename: data.filename || 'photo.jpg'
                                            };
                                            this.addLog('🇿 图片数据已更新到显示区域');
                                            this.$message.success('拍照成功，图片已更新!');
                                        } else {
                                            this.addLog('⚠️ 拍照消息中未找到图片数据');
                                        }
                                    } else if (data.device && data.timestamp) {
                                        console.log('消息类型: 设备状态');
                                        this.addLog(`📱 收到设备状态信息 - 设备: ${data.device}`);
                                        this.addLog(`⏰ 设备时间: ${this.formatTimestamp(data.timestamp)}`);
                                    } else {
                                        console.log('消息类型: 其他');
                                        this.addLog('📬 收到其他类型消息');
                                    }
                                    
                                    console.log('=== 消息处理完毕 ===\n');
                                    this.addLog('---消息处理完毕---');
                                    
                                } catch (error) {
                                    console.error('JSON解析错误:', error);
                                    console.log('非JSON消息:', messageString);
                                    this.addLog(`❌ JSON解析失败: ${error.message}`);
                                    this.addLog(`📝 非 JSON 格式消息，原始内容: ${messageString}`);
                                }
                            } else {
                                // 其他主题的消息
                                console.log(`收到非目标主题消息: ${topdata}`);
                                this.addLog(`⚠️ 收到非目标主题消息: ${topdata}`);
                            }
                        });
                        
                    } catch (error) {
                        this.connecting = false;
                        this.addLog('连接失败: ' + error.message);
                        this.$message.error('连接失败: ' + error.message);
                    }
                },
                
                // 断开MQTT连接
                disconnectMQTT() {
                    if (this.client) {
                        this.client.end();
                        this.client = null;
                        this.connected = false;
                        this.addLog('手动断开MQTT连接');
                        this.$message.info('已断开MQTT连接');
                    }
                },
                
                // 格式化时间戳
                formatTimestamp(timestamp) {
                    if (!timestamp) return '-';
                    return new Date(timestamp * 1000).toLocaleString('zh-CN');
                },
                
                // 显示大图
                showFullPhoto() {
                    this.showPhotoDialog = true;
                },
                
                // 拍照功能
                takePhoto() {
                    if (this.client && this.connected) {
                        const message = {
                            "type": "photo",
                            "filename": "my_photo",
                            "send": true
                        };
                        
                        const messageString = JSON.stringify(message);
                        
                        // 打印到控制台
                        console.log('=== MQTT 发送消息 ===');
                        console.log('命令类型: 拍照');
                        console.log('主题:', this.mqttConfig.topic);
                        console.log('消息对象:', message);
                        console.log('消息字符串:', messageString);
                        console.log('=== 发送完毕 ===\n');
                        
                        this.client.publish(this.mqttConfig.topic, messageString);
                        this.addLog(`发送拍照命令: ${messageString}`);
                        this.$message.success('拍照命令发送成功，请等待照片返回...');
                    } else {
                        console.log('发送失败: 未连接到MQTT服务器');
                        this.addLog('未连接到MQTT服务器，无法发送拍照命令');
                        this.$message.error('未连接到MQTT服务器');
                    }
                },
                sendLedCommand() {
                    if (this.client && this.connected && !this.ledActive) {
                        const message = {
                            "msg": "hello",
                            "type": "led"
                        };
                        
                        const messageString = JSON.stringify(message);
                        
                        // 打印到控制台
                        console.log('=== MQTT 发送消息 ===');
                        console.log('命令类型: LED控制');
                        console.log('主题:', this.mqttConfig.topic);
                        console.log('消息对象:', message);
                        console.log('消息字符串:', messageString);
                        console.log('=== 发送完毕 ===\n');
                        
                        // 激活闪光灯状态
                        this.ledActive = true;
                        
                        this.client.publish(this.mqttConfig.topic, messageString);
                        this.addLog(`发送消息到主题 ${this.mqttConfig.topic}: ${messageString}`);
                        this.addLog('💡 闪光灯已点亮，1秒后可再次使用');
                        this.$message.success('闪光灯已点亮！');
                        
                        // 1秒后恢复按钮状态
                        setTimeout(() => {
                            this.ledActive = false;
                            this.addLog('✅ 闪光灯冷卻完毕，可以再次点亮');
                        }, 1000);
                        
                    } else if (!this.connected) {
                        console.log('发送失败: 未连接到MQTT服务器');
                        this.addLog('未连接到MQTT服务器，无法发送消息');
                        this.$message.error('未连接到MQTT服务器');
                    } else if (this.ledActive) {
                        this.addLog('⚠️ 闪光灯正在冷卻中，请稍后再试');
                        this.$message.warning('闪光灯正在冷卻中，请稍后再试');
                    }
                },
                
                // 发送摄像头控制命令
                sendCameraCommand(direction) {
                    if (this.client && this.connected) {
                        const commandMap = {
                            'up': {
                                "msg": "camera_move",
                                "type": "camera",
                                "direction": "up",
                                "time": this.cameraTime
                            },
                            'down': {
                                "msg": "camera_move",
                                "type": "camera",
                                "direction": "down",
                                "time": this.cameraTime
                            },
                            'left': {
                                "msg": "camera_move",
                                "type": "camera",
                                "direction": "left",
                                "time": this.cameraTime
                            },
                            'right': {
                                "msg": "camera_move",
                                "type": "camera",
                                "direction": "right",
                                "time": this.cameraTime
                            }
                        };
                        
                        const message = commandMap[direction];
                        const messageString = JSON.stringify(message);
                        
                        const directionText = {
                            'up': '上',
                            'down': '下', 
                            'left': '左',
                            'right': '右'
                        };
                        
                        // 打印到控制台
                        console.log('=== MQTT 发送消息 ===');
                        console.log(`命令类型: 摄像头控制 [${directionText[direction]}]`);
                        console.log('主题:', this.mqttConfig.topic);
                        console.log('消息对象:', message);
                        console.log('消息字符串:', messageString);
                        console.log(`转动时间: ${this.cameraTime}秒`);
                        console.log('=== 发送完毕 ===\n');
                        
                        this.client.publish(this.mqttConfig.topic, messageString);
                        this.addLog(`发送摄像头控制命令 [${directionText[direction]}] 时间:${this.cameraTime}秒 - ${messageString}`);
                        this.$message.success(`摄像头${directionText[direction]}控制命令发送成功! (时间:${this.cameraTime}秒)`);
                    } else {
                        console.log('发送失败: 未连接到MQTT服务器');
                        this.addLog('未连接到MQTT服务器，无法发送消息');
                        this.$message.error('未连接到MQTT服务器');
                    }
                }
            }
        });
    </script>

    <style>
        body {
            margin: 0;
            background-color: #f5f5f5;
        }
        
        .box-card {
            max-width: 900px;
            margin: 20px auto;
        }
        
        .log-card {
            background-color: #fafafa;
        }
        
        .log-content {
            height: 300px;
            overflow-y: auto;
            background-color: #fff;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            padding: 10px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
        }
        
        .log-item {
            margin-bottom: 5px;
            line-height: 1.4;
        }
        
        .log-time {
            color: #909399;
            margin-right: 8px;
        }
        
        .log-message {
            color: #606266;
        }
        
        .clearfix:before,
        .clearfix:after {
            display: table;
            content: "";
        }
        .clearfix:after {
            clear: both;
        }
        
        /* 摄像头控制按钮样式 */
        .camera-control {
            background-color: #f9f9f9;
            border: 2px solid #e4e7ed;
            border-radius: 12px;
            padding: 20px;
            margin: 20px 0;
            max-width: 280px;
            margin-left: auto;
            margin-right: auto;
            text-align: center;
        }
        
        .camera-btn {
            width: 80px;
            height: 50px;
            font-weight: bold;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
        }
        
        .camera-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }
        
        .camera-btn:active {
            transform: translateY(0);
            box-shadow: 0 1px 2px rgba(0,0,0,0.1);
        }
        
        .camera-side {
            margin: 0 15px;
        }
        
        .camera-center-space {
            width: 45px;
            height: 45px;
        }
        
        /* 拍照按钮样式 */
        .photo-btn {
            width: 100px;
            height: 50px;
            font-weight: bold;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
        }
        
        .photo-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }
        
        /* 图片显示区域 */
        .photo-display {
            min-width: 300px;
        }
        
        .photo-container {
            border: 2px solid #e4e7ed;
            border-radius: 12px;
            padding: 15px;
            background-color: #fafafa;
            min-height: 280px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }
        
        .photo-placeholder {
            text-align: center;
            color: #c0c4cc;
        }
        
        .photo-image {
            max-width: 100%;
            max-height: 200px;
            border-radius: 8px;
            cursor: pointer;
            transition: transform 0.3s ease;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .photo-image:hover {
            transform: scale(1.05);
        }
        
        .photo-info {
            margin-top: 10px;
            font-size: 12px;
            color: #606266;
            text-align: left;
        }
        
        .photo-info p {
            margin: 5px 0;
        }
    </style>
</body>
</html>